
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.Gui;
using Swaf.Security;
using Swaf.Container;

namespace Forums.Gui
{
	public class ForumBizProc : Articles.Gui.ArticleManagementBizProc
	{
		public ForumBizProc(ActiveBizProc procState) : base(procState){}

		public override bool CanEdit
		{
			get
			{
				return base.CanEdit || State.InProgressAddBizObj != null;
			}
		}

		protected virtual string getAppFunctionNameForPost()
		{
			string appFun = "AppFunctions.ManageForumGroups";
			if (UsingAsUserComments)
			{
				IBizObj commentedItem = m_procState.get("associated") as IBizObj;
				if (commentedItem != null && commentedItem.containsField("metaType"))
				{
					string metaType = commentedItem.get("metaType").ToString();
					appFun = new StringBuilder(100).Append("AppFunctions.").Append(metaType).Append("UserComment").ToString();
				}
			}
			else if(m_currentBizObj != null)
			{
				int depth = (int)m_currentBizObj.get("depth");
				if (depth >= 2)
					appFun = "AppFunctions.ManageForumPosts";
			}
			return appFun;
		}

		public override Privileges CurrentEditPrivilege
		{
			get
			{
				Privileges priv = CurrentPrincipal.getPrivilege(getAppFunctionNameForPost());
				if (priv <= Privileges.ReadOnly)
				{
					IBizObj o = m_currentBizObj;
					if (o == null)
						o = m_procState.get("parent") as IBizObj;

					int depth = 0;
					if(o != null)
						depth = (int)o.get("depth");

					if ((State.InProgressAddBizObj != null || depth >= 2) &&
						CurrentPrincipal.getPrivilege("AppFunctions.CreateForumPosts") >= Privileges.AddOnly)
						priv = CurrentPrincipal.getPrivilege("AppFunctions.CreateForumPosts");
				}
				//if (priv < Privileges.Edit && State.InProgressAddBizObj != null)
				//	priv = Privileges.Edit;

				return priv;
			}
		}

		protected override string ArticleTreeName { get { return "Forum"; } }

		public override string UseAssociationName
		{
			get 
			{
				string assName = base.UseAssociationName;
				if (!Cmn.IsEmpty(assName))
					assName = new StringBuilder(assName.Length + 25).Append("AssociatedForums,GeneralForum,").Append(assName).ToString();
				return assName;
			}
		}

		public virtual bool UsingAsUserComments
		{
			get
			{
				return !Cmn.IsEmpty(State.State.get("useAssociationName"));
			}
		}

		protected override bool CreateParentsIfNoExist { get { return true; } }

		//public override IBizObj createNewBizObj()
		//{
		//    IBizObj f = base.createNewBizObj();

		//    //f.put("treeName", ArticleTreeName);
		//    //object pid = m_procState.get("pid");
		//    //IResults rc = App.ruleMgr.execute("getArticleDetail", pid, false, DetailLevel.idAndTitle, false, true);
		//    //IBizObj parent = rc.CallResults as IBizObj;
		//    //if (parent != null)
		//    //{
		//    //    f.put("parentId", parent.get("id"));
		//    //    int parentDepth = (int)parent.get("depth");
		//    //    if (parentDepth == 3)
		//    //        f.put("baseTitle", "Re: " + parent.get("baseTitle"));
		//    //    f.put("depth", parentDepth + 1);
		//    //}
		//    //else
		//    //{
		//    //    IBizObj parentForum = base.createNewBizObj();
		//    //    parentForum.put("treeName", ArticleTreeName);
		//    //    parentForum.put("id", new Swaf.BGuid.Guid());
		//    //    if (pid is string)
		//    //    {
		//    //        parentForum.put("uniqueTitle", pid);
		//    //        parentForum.put("baseTitle", pid);
		//    //    }
		//    //    rc = App.ruleMgr.execute("updateArticle", parentForum);
		//    //    if (rc == null)
		//    //        throw new BaseException("Cannot create parent article for forum to be created in");

		//    //    f.put("baseTitle", "");
		//    //    f.putValidated("parentId", parentForum.get("pid"));
		//    //}
		//    return f;
		//}

		protected override void getBizObjList()
		{
			base.getBizObjList();
			//if (m_bizobjs != null && CanEdit && (m_bizobjs.numElements == 0 || !m_bizobjs[m_bizobjs.numElements - 1].isNew))
			//    m_bizobjs.Add(createNewBizObj());
		}

		public override IResults updateBizObj(IBizObj obj)
		{
			if (UsingAsUserComments && obj.isDirty("publishAuthorName")
				&& Cmn.IsFalse(CurrentUser.get("authenticated")))
			{
				string name = (string)obj.get("publishAuthorName");
				IResults rc = App.ruleMgr.execute("filterAllHtml", name);
				if (rc.CallResults is string)
					name = (string)rc.CallResults;
				obj.put("publishAuthorName", string.Format("anonymous as <b>{0}</b>", name));
			}
			return base.updateBizObj(obj);
		}

		protected override object[] getDetailsBizRuleParameters(object bizObjKey)
		{
			object[] p = base.getDetailsBizRuleParameters(bizObjKey);
			if (p != null && p.Length == 4)
				if (Cmn.IsFalse(m_procState.get("incrementCounts")))
					p[3] = false;
				else
					p[3] = true;
			return p;
		}

		protected override void setupGetArticleListMacros(FlexiMap m)
		{
			m.put("objectTreeName", ArticleTreeName);
		}

		public override void clearRetrievedData()
		{
			//base.clearRetrievedData();
		}
		public override void updateActionState()
		{
			base.updateActionState();

			IBizObj o = CurrentBizObj;
			if (o == null)
				o = m_procState.get("parent") as IBizObj;

			int depth = 0;
			if(o != null && !CanEdit)
				depth = (int)o.get("depth");

			Privileges priv = CurrentPrincipal.getPrivilege(getAppFunctionNameForPost());

			if (priv <= Privileges.ReadOnly && !CanEdit &&
				depth >= 2 && CurrentPrincipal.getPrivilege("AppFunctions.CreateForumPosts") >= Privileges.AddOnly)
			{
				((GenericAction)Actions["AddBizObj"]).Availability = ActionAvailability.enabled;
			}
			else
			{
				if ((priv == Privileges.AddOnly || priv == Privileges.EditOnly || priv >= Privileges.Add) &&
					State.InProgressAddBizObj == null)
					((GenericAction)Actions["AddBizObj"]).Availability = ActionAvailability.enabled;
				if (priv < Privileges.Edit && UsingAsUserComments)
					((GenericAction)Actions["SwitchEdit"]).Availability = ActionAvailability.none;
			}
            ((GenericAction)Actions["TranslateAllChildren"]).Availability = ((GenericAction)Actions["DeleteBizObj"]).Availability;
		}

        protected override void setupActions()
        {
            base.setupActions();
            Actions.addAction(new GenericAction("TranslateAllChildren", false, translateAllChildren, this));
        }

        public void translateAllChildren()
        {
            App.ruleMgr.execute("translateForumThread", CurrentBizObjKeyValue);
        }

		protected override bool shouldCallGetBizObjListRule(object parentBizObjId)
		{
			if (UsingAsUserComments)
				return CurrentEditPrivilege >= Privileges.ReadOnly;
			return base.shouldCallGetBizObjListRule(parentBizObjId);
		}
	}
}
